package m.jclecai.com.ui;

import android.content.Intent;
import android.text.Editable;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnFocusChange;
import butterknife.OnTextChanged;
import m.jclecai.com.R;
import m.jclecai.com.activity.LoginActivity;
import m.jclecai.com.activity.LotteryPayActivity;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.IssueInfoBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.contents.LotteryType;
import m.jclecai.com.inter.OnResultCallback;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.OkHttpClientManager;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.ToastUtil;
import m.jclecai.com.utils.Validator;
import m.jclecai.com.utils.http.FastOk;

/**
 * Created by hp on 2017/5/27.
 * <p>
 * 发起合买页面
 */
public class JointPurchaseActivity extends BaseActivity {

    @BindView(R.id.tv_term)
    TextView tv_term;  //期号
    @BindView(R.id.tv_sum_money)
    TextView tv_sum_money;        //注数金额
    @BindView(R.id.rb_one)
    RadioButton rb_one;
    @BindView(R.id.rb_two)
    RadioButton rb_two;
    @BindView(R.id.rb_three)
    RadioButton rb_three;
    @BindView(R.id.rb_four)
    RadioButton rb_four;
    @BindView(R.id.et_actualMoney)
    EditText et_actualMoney;        //认购
    @BindView(R.id.et_pnum)
    EditText et_pnum;    //保底
    @BindView(R.id.et_desc)
    EditText et_desc;   //宣言
    @BindView(R.id.et_wrate)
    Spinner et_wrate;        //提成
    @BindView(R.id.tv_baseMoney)
    TextView tv_baseMoney;        //最少认购
    @BindView(R.id.tv_infos)
    TextView tv_infos;
    @BindView(R.id.tv_bd)
    TextView tvBd;
    int oflag = 0;
    String type;
    int totalNum;//注数
    int multiple;//倍数
    int totalMoney;//总金额
    int num;//追号期数
    float actualMoney;//认购
    float pnum;//保底
    String codes;
    String term;

    @Override
    protected int getContentView() {
        if (PreferenceUtil.getUserName(this).isEmpty()) {
            Intent i = new Intent(this, LoginActivity.class);
            startActivity(i);
        }
        return R.layout.joint_purchase_activity;
    }

    @Override
    protected void initView() {
        setTitle("发起合买");
        leftOptionText("返回");
        et_wrate.setSelection(5);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        totalNum = intent.getIntExtra("totalNum", 0);
        multiple = intent.getIntExtra("multiple", 0);
        totalMoney = intent.getIntExtra("totalMoney", 0);
        num = intent.getIntExtra("num", 0);
        codes = intent.getStringExtra("codes");
        pnum = 0;
        actualMoney = BaseUtils.getDecimalMoney(totalMoney * 0.05f, 2);
        boolean bool = Validator.isNumber(String.valueOf(actualMoney));
        if (!bool)
            actualMoney = (float) Math.ceil(actualMoney);
        if (actualMoney > 1) {
            et_actualMoney.setText(String.valueOf((int) actualMoney));
        } else {
            actualMoney = 1;
            et_actualMoney.setText("1");
        }
        updateTxt();
        getIssueInfo(type);
    }

    private void getIssueInfo(String type) {
        OkHttpClientManager.Param Url = new OkHttpClientManager.Param("url", Constant_Url.ISSUE_INFO);
        OkHttpClientManager.Param Type = new OkHttpClientManager.Param("type", type);
        OkHttpClientManager.Param[] param = new OkHttpClientManager.Param[]{Url, Type};
        try {
            OkHttpClientManager.getInstance().asynPost(new OnResultCallback() {

                @Override
                public void onGetResult(String json) {
                    IssueInfoBean bean = FastOk.get(json, IssueInfoBean.class);
                    setViewInfo(bean);
                }

                @Override
                public void onError() {
                    ToastUtil.showToast(JointPurchaseActivity.this, R.string.connect_failure);
                }
            }, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setViewInfo(IssueInfoBean bean) {
        if (bean == null) return;
        switch (BaseUtils.stringOfInt(type)) {
            case LotteryType.SSQ:
                tv_term.setText("双色球" + bean.getTermNo() + "期");
                break;
            case LotteryType.DLT:
                tv_term.setText("大乐透" + bean.getTermNo() + "期");
                break;
            case LotteryType.SD:
                tv_term.setText("3d" + bean.getTermNo() + "期");
                break;
            case LotteryType.SDXYXW:
                tv_term.setText("山东11选5" + bean.getTermNo() + "期");
                break;
            case LotteryType.CQSSC:
                tv_term.setText("重庆时时彩" + bean.getTermNo() + "期");
                break;
            case LotteryType.JSKS:
                tv_term.setText("江苏快三" + bean.getTermNo() + "期");
                break;
            case LotteryType.PLS:
                tv_term.setText("排列三" + bean.getTermNo() + "期");
                break;
            case LotteryType.PLW:
                tv_term.setText("排列五" + bean.getTermNo() + "期");
                break;
            case LotteryType.QXC:
                tv_term.setText("七星彩" + bean.getTermNo() + "期");
                break;
            case LotteryType.QLC:
                tv_term.setText("七乐彩" + bean.getTermNo() + "期");
                break;
        }
        term = bean.getTermNo();
    }

    @OnClick({R.id.tv_buy, R.id.rb_one, R.id.rb_two, R.id.rb_three, R.id.rb_four})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_buy:       //确定合买
                showBuyInfo();
                break;
            case R.id.rb_one:
                rb_one.setChecked(true);
                rb_two.setChecked(false);
                rb_three.setChecked(false);
                rb_four.setChecked(false);
                oflag = 0;
                break;
            case R.id.rb_two:
                rb_one.setChecked(false);
                rb_two.setChecked(true);
                rb_three.setChecked(false);
                rb_four.setChecked(false);
                oflag = 1;
                break;
            case R.id.rb_three:
                rb_one.setChecked(false);
                rb_two.setChecked(false);
                rb_three.setChecked(true);
                rb_four.setChecked(false);
                oflag = 2;
                break;
            case R.id.rb_four:
                rb_one.setChecked(false);
                rb_two.setChecked(false);
                rb_three.setChecked(false);
                rb_four.setChecked(true);
                oflag = 3;
                break;
        }
    }

    private void showBuyInfo() {

        Log.e(TAG, "totalNum=" + totalNum);
        Log.e(TAG, "multiple=" + multiple);
        Log.e(TAG, "totalMoney=" + totalMoney);
        Log.e(TAG, "et_actualMoney=" + actualMoney);
        Log.e(TAG, "et_pnum=" + et_pnum.getText().toString());
        Log.e(TAG, "et_desc=" + et_desc.getText().toString());
        Log.e(TAG, "codes=" + codes.substring(0, codes.length() - 1));
        Log.e(TAG, "type=" + type);
        Log.e(TAG, "num=" + num);
        Log.e(TAG, "term=" + term);
        Log.e(TAG, "et_wrate=" + et_wrate.getSelectedItem().toString());
        Log.e(TAG, "oflag=" + oflag);
        if (actualMoney <= 0) {
            DisPlay("认购金额不能小于5%");
            return;
        }
        /**
         * 此处提交之前先判断用户是否登录
         */
        Intent intent = new Intent(this, LotteryPayActivity.class);
        intent.putExtra(PAY_VOTENUMS, String.valueOf(totalNum)); //注数
        intent.putExtra(PAY_MULTIPLE, String.valueOf(multiple)); //倍数
        intent.putExtra(PAY_MONEY, String.valueOf(totalMoney));//金额
        intent.putExtra(PAY_BNUM, String.valueOf(actualMoney)); //认购
        intent.putExtra(PAY_PNUM, String.valueOf(pnum));//保底
        intent.putExtra(PAY_DESC, et_desc.getText().toString());//宣言
        intent.putExtra(PAY_CODES, codes.substring(0, codes.length() - 1)); //球
        intent.putExtra(PAY_TYPE, type);//彩种
        intent.putExtra(PAY_NAME, "合买");//方案标题
        intent.putExtra(PAY_NUM, String.valueOf(num));//追号期数
        intent.putExtra(PAY_TERM, term);//当前期号
        intent.putExtra(PAY_WRATE, et_wrate.getSelectedItem().toString());//提成
        intent.putExtra(PAY_PROJECETYPE, "1");//
        intent.putExtra(PAY_OFLAG, String.valueOf(oflag));//保密模式
        //这里控制对话框；
        intent.putExtra(LotteryPayActivity.IS_CAN_USE_RED_PACKET,false);
        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
    }

    @OnTextChanged(R.id.et_actualMoney)
    public void actualTxtChange(Editable s) {
        String acMoney = s.toString();
        //至少购买5%的金额
        actualMoney = BaseUtils.getDecimalMoney(totalMoney * 0.05f, 2);
        if (!acMoney.isEmpty()) {
            actualMoney = Float.valueOf(acMoney);
            if (acMoney.startsWith("0") && acMoney.length() > 1)
                et_actualMoney.setText(String.valueOf((int) actualMoney));
        } else {
            //允许删除后自己填写值
//            et_actualMoney.setText(String.valueOf(actualMoney));
            actualMoney = 0;
        }
        updateTxt();
        if (pnum > totalMoney - actualMoney)
            pnum = totalMoney - actualMoney;
        et_pnum.setText(String.valueOf((int) pnum));
    }

    //失去焦点判断值
    @OnFocusChange(R.id.et_actualMoney)
    void actualFocusChange(View v, boolean focus) {
        if (!focus) {
            float least = BaseUtils.getDecimalMoney(totalMoney * 0.05f, 2);
            if (least > actualMoney) {
                actualMoney = least;
                boolean bool = Validator.isNumber(String.valueOf(actualMoney));
                if (!bool)
                    actualMoney = (float) Math.ceil(actualMoney);
                if (actualMoney > 1) {
                    et_actualMoney.setText(String.valueOf((int) actualMoney));
                } else {
                    actualMoney = 1;
                    et_actualMoney.setText("1");
                }
                updateTxt();
            }
        }
    }

    //保底
    @OnClick(R.id.cb_all)
    void buyAll(View v) {
        boolean checked = ((CheckBox) v).isChecked();
        if(checked)
            pnum = totalMoney - actualMoney;
        et_pnum.setEnabled(!checked);
        et_pnum.setText(String.valueOf((int) pnum));
        updateTxt();
    }

    @OnTextChanged(R.id.et_pnum)
    void pnumChange(Editable s) {
        String pMoney = s.toString();
        if (!pMoney.isEmpty()) {
            pnum = Float.valueOf(pMoney);
            if (pMoney.startsWith("0") && pMoney.length() > 1)
                et_pnum.setText(String.valueOf((int) pnum));
            if (pnum > totalMoney - actualMoney) {
                pnum = totalMoney - actualMoney;
                et_pnum.setText(String.valueOf((int) pnum));
            }
        } else {
            //允许删除后自己填写值
//              et_pnum.setText(String.valueOf((int) pnum));
            pnum = 0;
        }
        updateTxt();
    }

    void updateTxt() {
        float bd = (pnum) / 1.0f / totalMoney * 100f;
        bd = BaseUtils.getDecimalMoney(bd, 2);
        tvBd.setText(Html.fromHtml(
                String.format(getString(R.string.join_purchase_bd),
                        String.valueOf(bd))
        ));

        float rg = (actualMoney) / 1.0f / totalMoney * 100f;
        rg = BaseUtils.getDecimalMoney(rg, 2);
        tv_baseMoney.setText(Html.fromHtml(
                String.format(getString(R.string.join_purchase_bd),
                        String.valueOf(rg))
        ));
        if (actualMoney > totalMoney) {
            actualMoney = totalMoney;
            et_actualMoney.setText(String.valueOf(totalMoney));
        } else if (actualMoney < 1 && actualMoney > 0) {
            et_actualMoney.setText(String.valueOf(1));
        }
        tv_infos.setText(Html.fromHtml(
                String.format(getString(R.string.join_purchase_tj), actualMoney, pnum, actualMoney + pnum)
        ));
        tv_sum_money.setText(Html.fromHtml(
                String.format(getString(R.string.join_purchase_t), totalNum, multiple, totalMoney)
        ));
    }
}
